/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

 
/**
 *
 * @author jarda
 */

class Homework4 extends MessageVisitor {
    public Homework4(Peer peer) {
        super(peer);
    }
 
   

    @Override
    boolean visitHaveMessage(HaveMessage message) {
       peer.peers2BlocksMap.get(message.sender)[message.blockIndex]=true;
       
       return false;
    }

    @Override
    boolean visitRequestMessage(RequestMessage message) {
       
        if(peer.data[message.blockIndex]!=null){
            message.sender.piece(peer, message.blockIndex, peer.data[message.blockIndex]);
            
        }
        
        
        return false;
    }

    @Override
    boolean visitPieceMessage(PieceMessage message) {
        peer.data[message.blockIndex]=message.data;
        peer.downloadedBlocksCount++;
        for (Map.Entry<PeerInterface,boolean[]> entry :peer.peers2BlocksMap.entrySet()){
            entry.getKey().have(peer, message.blockIndex);
        
        }
        return peer.downloadedBlocksCount==peer.totalBlocksCount;
    }

    @Override
    boolean visitIdleMessage(IdleMessage message) {
        int[] blocks=new int[peer.totalBlocksCount];
        int mostRareIndex=-1,lowestNumber=-1;
        for (Map.Entry<PeerInterface,boolean[]> entry :peer.peers2BlocksMap.entrySet()){
            for(int i=0; i<peer.totalBlocksCount;i++){
                if(entry.getValue()[i]){
                    blocks[i]+=1;
                }
            }
        }
        for(int y=0;y<blocks.length;y++){
            if(blocks[y]<lowestNumber || lowestNumber==-1){
                mostRareIndex=y;
            }
            
        }
        for (Map.Entry<PeerInterface,boolean[]> entry :peer.peers2BlocksMap.entrySet()){
            if(entry.getValue()[mostRareIndex]){
                entry.getKey().request(peer, mostRareIndex);
                break;
            }
        
        }
        
        return false;
    }

}

